package com.cskaoyan.service.impl;

import com.cskaoyan.bean.Ad;
import com.cskaoyan.bean.AdExample;
import com.cskaoyan.bean.BasePageData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.mapper.AdMapper;
import com.cskaoyan.service.AdService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Description
 * 广告的实现类
 *
 * @author Zhangfei
 * @date Created on 2021/10/18
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class AdServiceImpl implements AdService {

    @Autowired
    AdMapper adMapper;

    /**
     * 通过分页条件查询广告
     *
     * @param name
     * @param content
     * @param param
     * @return
     */
    @Override
    public BasePageData list(String name, String content, BaseParam param) {
        //配置分页信息
        PageHelper.startPage(param.getPage(), param.getLimit());


        //构造查询条件
        AdExample example = new AdExample();
        //根据参数判断是否为null，不为null则拼接条件
        AdExample.Criteria criteria = example.createCriteria();
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (content != null && !"".equals(content)) {
            criteria.andContentLike("%" + content + "%");
        }
        criteria.andDeletedEqualTo(false);
        //添加排序条件
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        //查询
        List<Ad> ads = adMapper.selectByExample(example);
        return BasePageData.ok(ads);
    }


    /**
     * 添加广告
     *
     * @param ad
     * @return
     */
    @Override
    public Ad create(Ad ad) {
        ad.setAddTime(new Date());
        ad.setUpdateTime(new Date());
        ad.setDeleted(false);
        //添加广告
        Integer count = adMapper.insertSelective(ad);

        //通过主键返回相应广告
        Ad adToReturn = null;
        if (count != 0) {
            adToReturn = adMapper.selectByPrimaryKey(ad.getId());
        }
        return adToReturn;
    }


    /**
     * 修改广告
     *
     * @param ad
     * @return
     */
    @Override
    public Ad update(Ad ad) {
        //设置更新日期
        ad.setUpdateTime(new Date());
        adMapper.updateByPrimaryKeySelective(ad);

        //通过主键返回相应广告
        Ad adToReturn = adMapper.selectByPrimaryKey(ad.getId());
        return adToReturn;
    }

    /**
     * 删除广告
     *
     * @param ad
     * @return
     */
    @Override
    public Integer delete(Ad ad) {
        ad.setUpdateTime(new Date());
        ad.setDeleted(true);
        return adMapper.updateByPrimaryKeySelective(ad);
    }


}
